package com.itheima.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.model.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/users/hello")
    @ResponseBody
    public String hello(){
        return "Hello users";
    }

    @RequestMapping("/user1")
    public ModelAndView user1(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/jsp/user1.jsp");
        return modelAndView;
    }

    @RequestMapping("/user2")
    @ResponseBody
    public User getUser(){
        User user = userService.getUser();
        System.out.println(user);
        return user;
    }


    @RequestMapping("/user4")
    @ResponseBody
    public String user4() throws JsonProcessingException {
        System.out.println("user4");
        User user = userService.getUser();
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(user);
    }

    @RequestMapping("/user5/{name}")
    @ResponseBody
    public String user5(@PathVariable(value = "name") String name){
        return name;
    }

    @RequestMapping("/user6")
    public ModelAndView user6(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/jsp/user1.jsp");
        return modelAndView;
    }

    @RequestMapping("/ajax")
    @ResponseBody
    public String user6(List<User> users){
        for (User user : users) {
            System.out.println(user);
        }
        return "hello";
    }

}
